'use strict';

/* Controllers */

angular.module('app')
  .controller('AppCtrl', ['$scope', '$translate', '$localStorage', '$window','$http','$modal','$rootScope',
    function(              $scope,   $translate,   $localStorage,   $window ,$http,$modal,$rootScope) {
      // add 'ie' classes to html
      var isIE = !!navigator.userAgent.match(/MSIE/i);
      isIE && angular.element($window.document.body).addClass('ie');
      isSmartDevice( $window ) && angular.element($window.document.body).addClass('smart');
      requestServlet("getUserInfo",{},function(rs){
        $scope.userInfo = rs;
      },function(msg){});
      requestServlet("getMyTaskNumber",{},function(rs){
        $scope.taskCount = rs;
      },function(msg){});
      $scope.refreshTaskCount = function(){
        requestServlet("getMyTaskNumber",{},function(rs){
          $scope.taskCount = rs;
        },function(msg){});
      }
      requestServlet("getMyProcessNumber",{},function(rs){
        $scope.processCount = rs;
      },function(msg){});
      $scope.refreshProcessCount = function(){
        requestServlet("getMyProcessNumber",{},function(rs){
          $scope.processCount = rs;
        },function(msg){});
      }
      requestServlet("getApplications",{},function(rs){
        $scope.applications = rs;
      },function(msg){});

      requestServlet("getBookmarks",{},function(rs){
        $scope.getbookmarks = rs;
      },function(msg){});
      $scope.refreshBookmarks = function(){
        requestServlet("getBookmarks",{},function(rs){
          $scope.getbookmarks = rs;
        },function(msg){});
      }
      $rootScope.userPhotoTimestamp = 0;
      // config
      $scope.app = {
        name: 'IdealBPM',
        version: 'v 2.2.0',
        // for chart colors
        color: {
          primary: '#7266ba',
          info:    '#23b7e5',
          success: '#27c24c',
          warning: '#fad733',
          danger:  '#f05050',
          light:   '#e8eff0',
          dark:    '#3a3f51',
          black:   '#1c2b36'
        },
        settings: {
          themeID: 1,
          navbarHeaderColor: 'bg-black',
          navbarCollapseColor: 'bg-white-only',
          asideColor: 'bg-black',
          headerFixed: true,
          asideFixed: false,
          asideFolded: false,
          asideDock: false,
          container: false
        }
      }

      // save settings to local storage
      if ( angular.isDefined($localStorage.settings) ) {
        $scope.app.settings = $localStorage.settings;
      } else {
        $localStorage.settings = $scope.app.settings;
      }
      $scope.$watch('app.settings', function(){
        if( $scope.app.settings.asideDock  &&  $scope.app.settings.asideFixed ){
          // aside dock and fixed must set the header fixed.
          $scope.app.settings.headerFixed = true;
        }
        // save to local storage
        $localStorage.settings = $scope.app.settings;
      }, true);

      // angular translate
      $scope.lang = { isopen: false };
      //$scope.langs = {en_US:'English', zh_CN:'中文', it_IT:'Italian'};
      $scope.langs = {zh_CN:'中文'};
      $scope.selectLang = $scope.langs[$translate.proposedLanguage()] || "English";
      $scope.selectLangCode = $translate.proposedLanguage()||"en_US";
      $scope.setLang = function(langKey, $event) {
        // set the current lang
        $scope.selectLangCode=langKey;
        $scope.selectLang = $scope.langs[langKey];
        // You can change the language during runtime
        $translate.use(langKey);
        $scope.lang.isopen = !$scope.lang.isopen;
      };

      function isSmartDevice( $window )
      {
          // Adapted from http://www.detectmobilebrowsers.com
          var ua = $window['navigator']['userAgent'] || $window['navigator']['vendor'] || $window['opera'];
          // Checks for iOs, Android, Blackberry, Opera Mini, and Windows mobile devices
          return (/iPhone|iPod|iPad|Silk|Android|BlackBerry|Opera Mini|IEMobile/).test(ua);
      }

      $scope.openPromptModal = function(title,content,callback){
          var modalInstance = $modal.open({
            templateUrl: 'tpl/prompt_modal.html',
            controller: 'promptModalCtrl',
            size: "sm",
            resolve: {
              title: function () {return title},
              content:function () {return content}
            }
          });
          modalInstance.result.then(function () {
            callback();
          }, function () {
            //dismiss
          });

      }
	  $scope.ws = io.connect('http://'+document.domain+':8877');
	  $scope.ws.emit('registerUser',$scope.userInfo.userName);
	  $scope.ws.isLoadTask = false;
	  $scope.ws.isLoadNews = false;
}]).controller('promptModalCtrl', ['$scope', '$modalInstance', 'title','content', function($scope, $modalInstance, title,content) {
  $scope.title = title;
  $scope.content = content;
  $scope.ok = function () {
    $modalInstance.close();
  };
  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
}]).controller('selectUsersModalCtrl', ['$scope', '$modalInstance','selectedUserAndGroups', function($scope, $modalInstance,selectedUserAndGroups) {
  $scope.userAndGroups;
  $scope.selectedUserAndGroups=JSON.parse(JSON.stringify(selectedUserAndGroups));
  $scope.type=0;
  $scope.selectedUserAndGroup={};
  $scope.getAllUsers = function () {
    $scope.type=0;
    requestServlet("searchUsers", {searchValue:$("#searchUserValue").val(),operator:2}, function (rs) {
        $scope.userAndGroups = rs.list;
      }, function (msg) {
      });
  };
  $scope.getAllUsers();
  $scope.setType = function (value) {
    $scope.type = value;
    $scope.selectedUserAndGroup={};
    if(value=="0"){
      $scope.getAllUsers();
    }else if(value=="1"||value=="2"){
      $scope.getUserAndGroups();
    }else if(value=="3"){
      $scope.getSubordinate();
    }
  }
  $scope.getUserAndGroups = function () {
      requestServlet("getUsesAndGroups", {type:$scope.type,id:$scope.selectedUserAndGroup.id}, function (rs) {
        $scope.userAndGroups = rs.list;
      }, function (msg) {
      });
  }
  $scope.findUserAndGroup = function (userAndGroup) {
    userAndGroup["backUserAndGroup"] = $scope.selectedUserAndGroup;
    $scope.selectedUserAndGroup = userAndGroup;
    $scope.getUserAndGroups();
  }
  $scope.backGroup = function () {
    requestServlet("getUsesAndGroups", {type:$scope.type,id:$scope.selectedUserAndGroup.backUserAndGroup.id}, function (rs) {
      $scope.userAndGroups = rs.list;
      if($scope.selectedUserAndGroup==null){
        $scope.selectedUserAndGroup={};
      }else{
        $scope.selectedUserAndGroup=$scope.selectedUserAndGroup.backUserAndGroup;
      }
    }, function (msg) {
    });
  }
  $scope.getSubordinate = function () {
    requestServlet("getSubordinate", {}, function (rs) {
      $scope.userAndGroups = rs.list;
    }, function (msg) {
    });
  }

  $scope.selectUserAndGroups = function (userAndGroup) {
    for(var i=0;i<$scope.selectedUserAndGroups.length;i++){
      if($scope.selectedUserAndGroups[i].id == userAndGroup.id){
        return;;
      }
    }
    $scope.selectedUserAndGroups.push(userAndGroup);
  }

  $scope.cleanUserAndGroup = function (userAndGroup) {
    for(var i=0;i<$scope.selectedUserAndGroups.length;i++){
      if($scope.selectedUserAndGroups[i].id == userAndGroup.id){
        $scope.selectedUserAndGroups.splice(i,1);
      }
    }
  }
  $scope.ok = function () {
      $modalInstance.close($scope.selectedUserAndGroups);
  };
  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
}]).controller('documentsViewModalCtrl', ['$scope', '$modalInstance','type', 'documentIds','documentId','scope','$modal','toaster','$filter','viewIndex', function($scope, $modalInstance,type, documentIds,documentId,scope,$modal,toaster,$filter,viewIndex) {
  $scope.type= type;
  $scope.documentIds = documentIds;
  $scope.documentId = documentId;
  $scope.document;
  $scope.documentView ;
  $scope.viewIndex = viewIndex;
  $scope.rotate = 0;
  $scope.close = function () {
    $modalInstance.close();
  };
  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
  $scope.timestamp = 0;
  $scope.getDocumentInfo = function () {
    requestServlet("getDocumentInfo", {id:$scope.documentId}, function (rs) {
      $scope.document = rs;
      $scope.documentView = rs;
    }, function (msg) {
    });
  };
  $scope.getDocumentInfo();
  $scope.prev = function () {
    if($scope.viewIndex<=0){
      return;
    }else{
      $scope.viewIndex=$scope.viewIndex-1;
      $scope.documentId = $scope.documentIds[$scope.viewIndex];
      $scope.getDocumentInfo();
    }
  };
  $scope.next = function () {
    if($scope.viewIndex>=documentIds.length-1){
      return;
    }else{
      $scope.viewIndex=$scope.viewIndex+1;
      $scope.documentId = $scope.documentIds[$scope.viewIndex];
      $scope.getDocumentInfo();
    }
  };
  $scope.versionSelect = function (index) {
    $scope.documentView = $scope.document.versions[index];
    for(var i=0;i<$scope.document.versions.length;i++){
      if(i==index){
        $scope.document.versions[i].selected = true;
      }else{
        $scope.document.versions[i].selected = false;
      }
    }
  };
  $scope.deleteDocument = function (id){
    scope.openPromptModal("common.prompt","common.ifDelete",function(){
      requestServlet("deleteContent",{id:id},function(){
        $modalInstance.close("delete");
      },function(msg){});
    });
  }
  $scope.moveDocument = function (id,type,name){
    var modalInstance = $modal.open({
      templateUrl: 'tpl/select_documents_modal.html',
      controller: 'selectDocumentsModalCtrl',
      size: "selectDoc",
      resolve: {
        type:function(){ return "move"; },
        documentName:function(){ return name; }
      }
    });
    modalInstance.result.then(function (parentIds) {
      requestServlet("updateContent",{id:id,type:type,name:name,parentId:parentIds[0]},function(){
        $modalInstance.close('move');
      },function(msg){});

    }, function () {
      //dismiss
    });
  }
  $scope.pooledDocument = function (id,type,name){
    var modalInstance = $modal.open({
      templateUrl: 'tpl/select_documents_modal.html',
      controller: 'selectDocumentsModalCtrl',
      size: "selectDoc",
      resolve: {
        type:function(){ return "pooled"; },
        documentName:function(){ return name; }
      }
    });
    modalInstance.result.then(function (parentIds) {
      requestServlet("copyContent",{id:id,parentId:parentIds[0]},function(){
        toaster.pop("success","common.prompt","common.documentPooledSuccess",null,null,function(){});
      },function(msg){});

    }, function () {
      //dismiss
    });
  }

  $scope.submitUpdateContentView = function (id,name,type,description){
    requestServlet("updateContent",{id:id,type:type,name:name,description:description},function(){
      $scope.getDocumentInfo();
      scope.getDocumentsByFolder();
    },function(msg){});

  }
  $scope.selectedFileNewVersion = function (thiss){
    $scope.$apply(function($scope) {
      toaster.pop("wait","common.prompt","common.documentUpLoadLoading",2000,null,function(){});
    });
    uploadFileById(thiss,function(rs){
      $scope.$apply(function($scope) {
        toaster.pop("success","common.prompt","common.documentSuccess",null,null,function(){});
        $scope.timestamp = $scope.timestamp +1;
        $scope.getDocumentInfo();
        scope.timestamp = scope.timestamp +1;
        //scope.getDocumentsByFolder();
      });
    })
  }
  //收藏切换
  $scope.setFavorite = function(id,favorite){
    if(favorite){
      favorite = 1;
    }else{
      favorite = 0;
    }
    requestServlet("setContentFavorite",{is_favorite:favorite,id:id},function(rs){
      scope.getDocumentsByFolder();
    },function(msg){});
  }
}]).controller('selectDocumentsModalCtrl', ['$scope', '$modalInstance','type','documentName', function($scope, $modalInstance,type,documentName) {
  $scope.type = type;
  $scope.documentName = documentName;
  $scope.foldersTrees = [];
  $scope.folder;
  $scope.folderType;
  $scope.isLoadMyDocument = true;
  $scope.isLoadDocument = true;
  if($scope.type=='pooled'){
    $scope.isLoadMyDocument=false;
    $scope.isLoadDocument=false;
  }
  if($scope.type=='move'){
    $scope.isLoadDocument=false;
  }
  $scope.getFolders = function(index) {
    requestServlet("getDocumentsAndFolders", {
      folderId: $scope.folder, isFavorite: false,isLoadDocument:$scope.isLoadDocument,isLoadMyDocument:$scope.isLoadMyDocument,
      searchValue: null,
      startIndex: 0,
      batchSize: -1
    }, function (rs) {
      if(index==0){
        $scope.folder =rs.list[0].id;
        rs.list[0].selected = true;
      }
      if($scope.foldersTrees[index]==null){
        $scope.foldersTrees.push({index: index,children:rs.list});
      }else{
        $scope.foldersTrees[index] = {index: index,children:rs.list};
      }


    }, function (msg) {
    });
  }
  $scope.getFolders(0);
  $scope.getFolders(1);
  $scope.selectFolder = function (id,index,treeIndex,type) {
    var folders = $scope.foldersTrees[treeIndex].children;
    for(var i=0;i<folders.length;i++){
      if(folders[i].id==id){
        $scope.foldersTrees[treeIndex].children[i].selected = true;
      }else{
        $scope.foldersTrees[treeIndex].children[i].selected = false;
      }
    }
    var foldersTrees = [];
    for (var i=0;i<treeIndex+1;i++){
      foldersTrees.push($scope.foldersTrees[i]);
    }
    $scope.foldersTrees = foldersTrees;
    $scope.folder = id;
    $scope.folderType = type;
    $scope.getFolders(treeIndex+1);
    $('.picker-column').animate({scrollLeft:9999},50)
  };

  $scope.close = function () {
    $modalInstance.close();
  };
  $scope.ok = function () {
    $modalInstance.close([$scope.folder]);
  };
}]);
